<template>
    <div class="kyc">
      <div class="header">
        <div class="back" @click="handleBack">
          <van-icon name="arrow-left" class="home-icon" />
        </div>
        <div class="title">Verification Info</div>
      </div>
  
      <div class="form-container">
        <!-- Gender Selection -->
        <div class="form-item">
          <div class="form-row">
            <div class="label">Gender</div>
            <div class="radio-group horizontal">
              <div 
                class="radio-item" 
                :class="{ active: form.gender === '0' }"
                @click="form.gender = '0'"
              >
                <span>Male</span>
                <div class="radio-circle"></div>
              </div>
              <div 
                class="radio-item" 
                :class="{ active: form.gender === '1' }"
                @click="form.gender = '1'"
              >
                <span>Female</span>
                <div class="radio-circle"></div>
              </div>
            </div>
          </div>
        </div>
        <div class="divider"></div>
  
        <!-- Birth Date -->
        <div class="form-item">
          <div class="form-row">
            <div class="label">Birth Date</div>
            <div class="input-wrapper date-select" @click="showDatePicker = true">
              <span class="placeholder" :class="{ 'has-value': form.birthDate }">
                {{ form.birthDate || 'Select Date' }}
              </span>
            </div>
          </div>
        </div>
        <div class="divider"></div>
  
        <!-- ID Type Selection -->
        <div class="form-item">
          <div class="form-row">
            <div class="label">ID Type</div>
            <div class="radio-group horizontal">
              <div 
                class="radio-item" 
                :class="{ active: form.idType === '0' }"
                @click="form.idType = '0'"
              >
                <span>ID Card</span>
                <div class="radio-circle"></div>
              </div>
              <div 
                class="radio-item" 
                :class="{ active: form.idType === '1' }"
                @click="form.idType = '1'"
              >
                <span>Passport</span>
                <div class="radio-circle"></div>
              </div>
              <div 
                class="radio-item" 
                :class="{ active: form.idType === '2' }"
                @click="form.idType = '2'"
              >
                <span>Driver License</span>
                <div class="radio-circle"></div>
              </div>
            </div>
          </div>
        </div>
        <div class="divider"></div>
  
        <!-- ID Number -->
        <div class="form-item">
          <div class="form-row">
            <div class="label">ID Number</div>
            <div class="input-wrapper">
              <van-field 
                v-model="form.idNumber" 
                placeholder="Enter ID Number" 
              />
            </div>
          </div>
        </div>
        <div class="divider"></div>
  
        <!-- Surname -->
        <div class="form-item">
          <div class="form-row">
            <div class="label">Surname</div>
            <div class="input-wrapper">
              <van-field 
                v-model="form.surname" 
                placeholder="Enter Surname" 
              />
            </div>
          </div>
        </div>
        <div class="divider"></div>
  
        <!-- First Name -->
        <div class="form-item">
          <div class="form-row">
            <div class="label">First Name</div>
            <div class="input-wrapper">
              <van-field 
                v-model="form.firstName" 
                placeholder="Enter First Name" 
              />
            </div>
          </div>
        </div>
        <div class="divider"></div>
  
        <!-- ID Photos Upload -->
        <div class="form-item">
          <div class="upload-section">
            <div class="upload-title">ID Front Photo</div>
            <div class="upload-box">
              <input 
                type="file" 
                ref="frontInput" 
                class="file-input" 
                accept="image/*" 
                @change="handleFileChange($event, 'front')"
              >
              <van-icon name="plus" class="plus-icon" />
              <img v-if="form.idFrontPhoto" :src="form.idFrontPhoto" class="preview-image">
            </div>
          </div>
          <div class="divider"></div>
          <div class="upload-section">
            <div class="upload-title">ID Back Photo</div>
            <div class="upload-box">
              <input 
                type="file" 
                ref="backInput" 
                class="file-input" 
                accept="image/*" 
                @change="handleFileChange($event, 'back')"
              >
              <van-icon name="plus" class="plus-icon" />
              <img v-if="form.idBackPhoto" :src="form.idBackPhoto" class="preview-image">
            </div>
          </div>
        </div>
      </div>
  
      <van-button 
        class="submit-btn" 
        type="primary" 
        block
        @click="handleSubmit"
      >
        Submit
      </van-button>
  
      <!-- Date Picker -->
      <van-popup v-model:show="showDatePicker" position="bottom">
        <van-datetime-picker
          v-model="currentDate"
          :min-date="minDate"
          :max-date="maxDate"
          type="date"
          @confirm="confirmDate"
          @cancel="showDatePicker = false"
        />
      </van-popup>
    </div>
  </template>
  
  <script setup name="Kyc">
  import { ref, reactive } from 'vue';
  import { Icon as VanIcon, Field as VanField, Button as VanButton, Popup as VanPopup, DatetimePicker, Toast } from 'vant';
  import { useRouter } from 'vue-router';
  import { uploadImage } from '../api/upload.api.ts';
  import { UserApi } from '../api/user.api';
  const router = useRouter();
  const form = reactive({
    gender: '',
    birthDate: '',
    idType: 'idCard',
    idNumber: '',
    surname: '',
    firstName: '',
    idFrontPhoto: '',
    idBackPhoto: ''
  });
  const unserInfo = ref({});
const getInfo = () => {
  UserApi.wallet().then(res => {
    if (res.code == 200) {
      // Handle wallet data here
      unserInfo.value = res.data;
    }
  });
};
  const showDatePicker = ref(false);
  const currentDate = ref([]);
  const minDate = new Date(1926, 0, 1);
  const maxDate = new Date();
  const frontInput = ref(null);
  const backInput = ref(null);
  
  const handleBack = () => {
    // Handle back navigation
    console.log('Navigate back');
    router.go(-1);
  };
  
  const confirmDate = (date) => {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    form.birthDate = `${year}-${month}-${day}`;

    showDatePicker.value = false;
  };
  

  
  const handleFileChange = async (event, type) => {
    const file = event.target.files[0];
    if (file) {
      try {
        const url = await uploadImage(file);
        if (type === 'front') {
          form.idFrontPhoto = url;
        } else {
          form.idBackPhoto = url;
        }
        // 重置input值以允许重复选择同一文件
        event.target.value = '';
      } catch (error) {
        Toast('Upload failed');
      }
    }
  };
  
  const handleSubmit = () => {
    // Validate form
    if (!form.gender) {
      Toast('Please select your gender');
      return;
    }
    if (!form.birthDate) {
      Toast('Please select your birth date');
      return;
    }
    if (!form.idNumber) {
      Toast('Please enter your ID number');
      return;
    }
    if (!form.surname || !form.firstName) {
      Toast('Please enter your full name');
      return;
    }
    if (!form.idFrontPhoto || !form.idBackPhoto) {
      Toast('Please upload both ID photos');
      return;
    }
    UserApi.setUserAuthentication({
      gender: Number(form.gender),
      birthday: form.birthDate,
      documentType: Number(form.idType),
      documentNumber: form.idNumber,
      surname: form.surname,
      name: form.firstName,
      documentFront: form.idFrontPhoto,
      documentBack: form.idBackPhoto, 
      userId: Number(unserInfo.value.id)
    }).then(res => {
      if (res.code == 200) {
        // Handle successful submission
        Toast.success('Verification submitted successfully');
        router.go(-1);
      } else {
        // Handle submission failure
        Toast.fail(res.msg);
      }
    });
    // Submit form
    console.log('Form submitted:', form);
    Toast.success('Verification submitted successfully');
  };
  getInfo();
  </script>
  
  <style scoped>
  .app-container{
    min-height: 100vh!important;
  }
  .kyc {
    min-height: 100vh;
    background: #f5f5f5;
  }
  
  .header {
    position: relative;
    height: 44px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #fff;
    border-bottom: 1px solid #f5f5f5;
  }
  
  .back {
    position: absolute;
    left: 0;
    top: 0;
    width: 44px;
    height: 44px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
  }
  
  .home-icon {
    width: 22px;
    height: 22px;
    font-weight: bold;
    margin-top: 6px;
  }
  
  .title {
    font-size: 16px;
    font-weight: 600;
    color: #333;
  }
  
  .form-container {
    margin: 12px;
    background: #fff;
    border-radius: 12px;
    overflow: hidden;
  }
  
  .form-item {
    padding: 15px;
    background: #fff;
    margin-bottom: 0;
    border-radius: 0;
  }
  
  .form-row {
    display: flex;
    align-items: center;
    width: 100%;
    height: 24px;
  }
  
  .label {
    font-size: 14px;
    color: #333;
    font-weight: 600;
    width: 80px;
    flex-shrink: 0;
  }
  
  .radio-group {
    display: flex;
    gap: 15px;
  }
  
  .radio-group.horizontal {
    display: flex;
    gap: 20px;
    justify-content: flex-end;
  }
  
  .radio-item {
    display: flex;
    align-items: center;
    cursor: pointer;
    box-sizing: border-box;
  }
  .radio-item span{
    font-size: 14px;
    color: #333;
  }
  .radio-group.horizontal .radio-item{
    display: flex;
    align-items: center;
    flex-direction: row-reverse;
    gap: 4px;
    cursor: pointer;
  }
  .radio-item.active .radio-circle {
    width: 18px;
    height: 18px;
    border: 1px solid #ddd;
    border-radius: 50%;
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .radio-item.active .radio-circle{
    background: rgb(48, 55, 232);
    border-color: #3037e8;
  }
  .radio-item.active .radio-circle::after {
    content: "";
    width: 10px;
    height: 6px;
    border: 2px solid #000;
    border-top: none;
    border-right: none;
    transform: rotate(-45deg);
    margin-top: -2px;
  }
  
  .radio-circle {
    width: 16px;
    height: 16px;
    border-radius: 50%;
    border: 1px solid #ccc;
  }
  
  .input-wrapper {
    flex: 1;
    padding-left: 30px;
  }
  
  .input-wrapper.date-select {
    width: 200px;
    height: 40px;
    border-radius: 8px;
    padding: 0 15px;
    cursor: pointer;
  }
  
  .placeholder {
    font-size: 14px;
    color: #999;
    line-height: 24px;
  }
  
  .placeholder.has-value {
    color: #333;
  }
  :deep(.van-field__control){
    width: 200px;
    border: none;
    outline: none;
    font-size: 14px;
    color: #333;
    padding: 0;
    background: transparent;
    caret-color: #3037e8;}
  .arrow-right {
    font-size: 12px;
    color: #969799;
  }
  
  .divider {
    height: 1px;
    background-color: #f5f5f5;
    margin: 0 15px;
  }
  
  .upload-section {
    padding: 15px 0;
  }
  
  .upload-title {
    font-size: 14px;
    color: #333;
    margin-bottom: 10px;
  }
  
  .upload-box {
    position: relative;
    width: 140px;
    height: 140px;
    border: 1px dashed #ddd;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #fff;
    cursor: pointer;
    overflow: hidden;
  }
  
  .file-input {
    position: absolute;
    width: 100%;
    height: 100%;
    opacity: 0;
    cursor: pointer;
  }
  
  .plus-icon {
    font-size: 24px;
    color: #969799;
  }
  
  .preview-image {
    position: absolute;
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
  
  .submit-btn {
    height: 40px;
    margin: 20px 0;
    background-image: linear-gradient(to right, rgb(48, 55, 232), rgb(94, 182, 237));
    border: 0px solid rgb(9, 17, 251);
    box-shadow: #0008ff33 0 2px 6px;
    color: #fff;
    border-radius: 22px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 16px;
    font-weight: 600;
    cursor: pointer;
  }
  </style>